package com.zl.java.util.utils.properties;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 读取properties资源文件工具包
 * Created by zhonglin on 2017/4/13.
 */
public class PropertiesUtils {

    /**
     * 读取properties资源文件并把值封装进Map集合中
     *
     * @param propertyFilePath 文件路径/文件名（在根目录下时直接填文件名）
     * @return
     */
    public static Map<String, String> toMap(String propertyFilePath) {

        Map<String, String> map         = new HashMap<>();
        Properties          properties  = null;
        InputStream         inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyFilePath);

        if (inputStream == null) {
            throw new IllegalArgumentException("Properties file not found in classpath: " + propertyFilePath);
        } else {
            try {
                properties = new Properties();
                properties.load(new InputStreamReader(inputStream, "UTF-8"));
            } catch (IOException e) {
                throw new RuntimeException("Error loading properties file.", e);
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Enumeration enums = properties.keys();
        while (enums.hasMoreElements()) {
            String key   = enums.nextElement() + "";
            String value = properties.getProperty(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * 读取properties资源文件单个值
     *
     * @param propertyFilePath 文件路径/文件名（在根目录下时直接填文件名）
     * @param key              属性名
     * @return
     */
    public static String getPropertieValue(
            String propertyFilePath,
            String key) {
        Map<String, String> propertyValueMap = toMap(propertyFilePath);
        return propertyValueMap.get(key);
    }

}
